package com.sanpu.kxe.business.repay.view;

import android.content.Context;
import android.content.DialogInterface;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.dialogplus.OnItemClickListener;
import com.sanpu.kxe.R;
import com.sanpu.kxe.base.BaseTitleActivity;
import com.sanpu.kxe.business.card.bean.BankInfoOutput;
import com.sanpu.kxe.business.card.view.AddBankSetupActivity;
import com.sanpu.kxe.business.main.bean.UserCenterOutput;
import com.sanpu.kxe.business.repay.bean.RepayCreditOutput;
import com.sanpu.kxe.business.repay.contract.AddCreditContract;
import com.sanpu.kxe.business.repay.contract.RepayConfig;
import com.sanpu.kxe.business.repay.model.RepayModel;
import com.sanpu.kxe.business.repay.presenter.AddCreditPresenter;
import com.sanpu.kxe.business.trade.adapter.ChooseBankAdapter;
import com.sanpu.kxe.common.cache.CacheManage;
import com.sanpu.kxe.common.cache.CacheModel;
import com.sanpu.kxe.common.interfaces.UrlConstants;
import com.sanpu.kxe.common.utils.CommonUtils;
import com.sanpu.kxe.common.utils.SingleCheckListener;
import com.sanpu.kxe.jump.eventbus.RefreshBankEvent;
import com.sanpu.kxe.jump.imageloader.JKImageLoader;
import com.sanpu.kxe.module.dialog.HintDialog;
import com.sanpu.kxe.utils.IntentTool;
import com.sanpu.kxe.utils.ToastUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Description：添加信用卡
 * Created by 薛勇军 on 2019/4/10.
 */

public class AddCreditActivity extends BaseTitleActivity implements AddCreditContract.View {

    @Bind(R.id.containLayout)
    LinearLayout containLayout;
    @Bind(R.id.nameTv)
    TextView nameTv;//持卡人
    @Bind(R.id.out_icon)
    ImageView vOutIcon;
    @Bind(R.id.out_bank_name)
    TextView vOutBankName;
    @Bind(R.id.tvPhoneNumber)
    TextView tvPhoneNumber;//开户行
    @Bind(R.id.billDayTv)
    TextView billDayTv;
    @Bind(R.id.refundDayTv)
    TextView refundDayTv;
    @Bind(R.id.billDayLl)
    LinearLayout billDayLl;
    @Bind(R.id.refundDayLl)
    LinearLayout refundDayLl;

    private SingleCheckListener singleCheckListener;

    private ChooseBankAdapter mBankAdapter;

    private AddCreditContract.Presenter mPresenter;

    private List<String> selectList = new ArrayList<>();

    private ArrayList<BankInfoOutput> mOutBankList = new ArrayList<>();

    private ArrayList<RepayCreditOutput.RepayCredit> cardList = new ArrayList<>();

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_add_credit;
    }

    @Override
    protected void initView() {
        super.initView();
        commonTitle.setTitle("绑定信用卡");
        mBankAdapter = new ChooseBankAdapter(mContext, new ArrayList<BankInfoOutput>());
    }

    @Override
    protected void initData() {
        super.initData();
        String apprtId = getIntent().getStringExtra(RepayConfig.INTENT_APPRTID);
        String cardListJson = getIntent().getStringExtra(RepayConfig.INTENT_CARDLIST);

        if (!TextUtils.isEmpty(cardListJson)) {
            cardList = new Gson().fromJson(cardListJson, new TypeToken<
                    ArrayList<RepayCreditOutput.RepayCredit>>() {
            }.getType());
        }
        UserCenterOutput centerOutput = CacheManage.getInstance().getCache(CacheModel.USER_CENTER_KEY);
        if (centerOutput != null && !TextUtils.isEmpty(centerOutput.getCrpNm())) {
            nameTv.setText(centerOutput.getCrpNm());
        }
        selectList = RepayModel.getInstance().getSelectList();
        mPresenter = new AddCreditPresenter(this, apprtId);
        mPresenter.selectUrmBankPage();
    }

    @OnClick({R.id.next, R.id.billDayLl, R.id.refundDayLl, R.id.cardHintIv, R.id.phone_hint, R.id.out_select_bank})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.next:
                BankInfoOutput infoOutput = (BankInfoOutput) vOutBankName.getTag();
                if (infoOutput == null) {
                    ToastUtil.show("请选择信用卡");
                    return;
                }
                String billDay = billDayTv.getText().toString();
                String refundDay = refundDayTv.getText().toString();
                mPresenter.onCommmit(infoOutput.getBankId(), billDay.substring(2, billDay.length() - 1),
                        refundDay.substring(2, refundDay.length() - 1));
                break;
            case R.id.billDayLl:
                if (singleCheckListener == null) {
                    singleCheckListener = new SingleCheckListener(AddCreditActivity.this);
                }
                singleCheckListener.handleCheck(containLayout, billDayTv, selectList);
                break;
            case R.id.refundDayLl:
                if (singleCheckListener == null) {
                    singleCheckListener = new SingleCheckListener(AddCreditActivity.this);
                }
                singleCheckListener.handleCheck(containLayout, refundDayTv, selectList);
                break;
            case R.id.cardHintIv:
                TextView textView = new TextView(mContext);
                textView.setText("为保障账户资金安全，只能绑定认证用户本人的信用卡。");
                new HintDialog(mContext)
                        .title("信用卡号说明")
                        .content(textView)
                        .show();
                break;
            case R.id.phone_hint:
                new HintDialog(mContext)
                        .title("手机号说明")
                        .content(CommonUtils.generateHintView(mContext, 0,
                                "银行预留手机号码是办理该银行卡所填写的手机号码。预留手机号忘记或已停用，请联系银行客服更新处理。"))
                        .show();
                break;
            case R.id.out_select_bank:
                bankDialog();
                break;
        }
    }

    /**
     * 提现银行卡对话框
     */
    private void bankDialog() {
        mBankAdapter.setCheckPosition(vOutBankName.getTag() != null ? mOutBankList.lastIndexOf(vOutBankName.getTag()) : -1);
        mBankAdapter.setNotifyData(mOutBankList);
        final View header = LayoutInflater.from(mContext).inflate(R.layout.layout_choose_bank_header, null);
        final DialogPlus dialog = DialogPlus.newDialog(this)
                .setAdapter(mBankAdapter)
                .setHeader(header)
                .setFooter(R.layout.layout_choose_credit_bank_foot)
                .setGravity(Gravity.CENTER)
                .setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(DialogPlus dialog, Object item, View view, int position) {
                        if (position < 0) return;
                        dialog.dismiss();
                        if (mOutBankList.size() == position) {
                            HintDialog hintDialog = new HintDialog(mContext)
                                    .title("添加信用卡号说明")
                                    .content(CommonUtils.generateHintView(mContext, 0,
                                            "添加新的信用卡后需重新进入当前页进行绑定信用卡"));
                            hintDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                                @Override
                                public void onDismiss(DialogInterface dialog) {
                                    IntentTool.startActivity(mContext, AddBankSetupActivity.class);
                                }
                            });
                            hintDialog.show();
                            return;
                        }
                        displayBank(mOutBankList.get(position));
                    }
                })
                .setExpanded(false)
                .create();
        dialog.show();

        header.findViewById(R.id.arrow).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    @Override
    public void showDataView(List<BankInfoOutput> bankInfoOutputs) {
        mOutBankList.clear();
        if (cardList != null && cardList.size() > 0) {
            for (BankInfoOutput infoOutput : bankInfoOutputs) {
                for (int index = 0; index < cardList.size(); index++) {
                    if (TextUtils.equals(infoOutput.getBankNo(), cardList.get(index).getCardNo())) {
                        break;
                    }
                    if (index == cardList.size() - 1) {
                        mOutBankList.add(infoOutput);
                    }
                }
            }
        } else {
            mOutBankList.addAll(bankInfoOutputs);
        }
        if (mOutBankList.size() > 0) {
            displayBank(mOutBankList.get(0));
        }
    }

    /**
     * 显示卡信息
     */
    private void displayBank(BankInfoOutput infoOutput) {
        try {
            JKImageLoader.getInstance().displayImage(
                    mContext,  UrlConstants.getBaseUrl() + infoOutput.getLogoPath(), vOutIcon);
            String bankNo = infoOutput.getBankNo();
            vOutBankName.setText(infoOutput.getBankName().replace(" ", "")
                    + "  (" + bankNo.substring(bankNo.length() - 4, bankNo.length()) + ")");
            vOutBankName.setTag(infoOutput);
        } catch (Exception e) {
            e.printStackTrace();
        }
        tvPhoneNumber.setText(infoOutput.getRsdTel() == null ? "" : infoOutput.getRsdTel());
        if (!TextUtils.isEmpty(infoOutput.getBillDay())) {
            billDayTv.setText("每月" + infoOutput.getBillDay() + "号");
            billDayLl.setEnabled(false);
        } else {
            billDayLl.setEnabled(true);
        }
        if (!TextUtils.isEmpty(infoOutput.getDueDay())) {
            refundDayTv.setText("每月" + infoOutput.getDueDay() + "号");
            refundDayLl.setEnabled(false);
        } else {
            refundDayLl.setEnabled(true);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshBank(RefreshBankEvent event) {
        if (event != null) {
            mPresenter.selectUrmBankPage();
        }
    }

    @Override
    protected boolean hasBindEventBus() {
        return true;
    }

    @Override
    public void setPresenter(AddCreditContract.Presenter presenter) {
        this.mPresenter = presenter;
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.onDestroyPresenter();
            mPresenter = null;
        }
    }
}
